package com.li.list;

public class 判断链表是否有环 {
	public static void main(String[] args) {
		Node head = new Node();
		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		Node node6 = new Node(6);

		head.next = node1;
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		node6.next = head;
		
		//printList(head);
		System.out.println(isHasCircle(head));
		//printList(head);
	}
	
	/**
	 * 判断链表是否有环,思路使用fast指针和low指针对链表进行遍历,fast追上slow则有环，否则无环
	 * @param head
	 * @return
	 */
	public static boolean isHasCircle(Node head){
		if(head == null || head.next ==null){
			return false;
		}
		Node fast = head.next;
		Node slow = head;
		while(fast!=slow){
			if(fast == null || fast.next ==null){
				return false;
			}
			fast = fast.next.next;
			slow = slow.next;
		}
		return true;
	}
	
	/**
	 * 打印链表
	 * @param head
	 */
	public static void printList(Node head){
		while((head = head.next)!=null){
			System.out.print(head.value+" ");
		}
		System.out.println();
	}
}
